package controller;

import com.google.gson.Gson;
import entry.*;
import exception.AppException;
import pojo.FinancingAndInstituty;
import pojo.FinancingCondition;
import pojo.VoucherAndTwoEnterpriseAndInstituty;
import pojo.VoucherCondition;
import service.*;
import service.impl.*;
import util.PageHelper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static constants.StringConstants.USER;

@WebServlet("/financing/*")
public class FinancingServlet extends HttpServlet {
   private  UserService userService = new UserServiceImpl();
    private FinancingService financingService = new FinancingServiceImpl();
    private VoucherService voucherService = new VoucherServiceImpl();
    private  InstitutyService institutyService = new InstitutyServiceImpl();
    private EnterpriseService enterpriseService = new EnterpriseServiceImpl();

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset = utf-8");

        String url = request.getRequestURI();
        String methodName = url.substring(url.lastIndexOf("/") + 1);
        Class clas = FinancingServlet.class;
        try {
            Method method = clas.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(this , request, response);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    //上使用反射调用方法，下为所有方法
    public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String account = request.getParameter("account");
        String password = request.getParameter("password");

        User selector = new User();
        selector.setAccount(account);
        selector.setPassword(password);
        Gson gson = new Gson();
        Map<String, Object> result = new HashMap<>();
        try {
            User user = userService.login(selector);
            request.getSession().setAttribute(USER, user);
            result.put("code", 1);
            result.put("user", user);
        } catch (AppException e) {
            result.put("code", 0);
            result.put("msg", e.getMsg());
        }
        response.getWriter().println(gson.toJson(result));
    }

    public void queryAll(HttpServletRequest request, HttpServletResponse response){
        String query = request.getParameter("query");
        String str = request.getParameter("str");
        FinancingCondition financingCondition = new FinancingCondition();
        Gson gson = new Gson();
        try {
            response.getWriter().println(gson.toJson(financingCondition));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void  queryByFinancingCondition(HttpServletRequest request, HttpServletResponse response){
        String enterprise_id = request.getParameter("enterprise_id");
        String no = request.getParameter("no");
        String instituty_id =request.getParameter("instituty_id");
        String amount_low = request.getParameter("amount_low");
        String amount_high =request.getParameter("amount_high");
        String create_time = request.getParameter("create_time");
        String status = request.getParameter("status");
        String whichPage = request.getParameter("whichPage");
        FinancingCondition financingCondition = new FinancingCondition();
        if (enterprise_id != null && enterprise_id != "")
            financingCondition.setInstituty_id(Integer.parseInt(enterprise_id));
        if (no != null && no != "")
            financingCondition.setNo(no);
        if(instituty_id != null && instituty_id != "")
            financingCondition.setInstituty_id(Integer.parseInt(instituty_id));
        if (amount_low != null && amount_low != ""){
            financingCondition.setAmount_low(Double.parseDouble(amount_low));
            financingCondition.setAmount_low(financingCondition.getAmount_low() * 10000);
        }
        if (amount_high != null && amount_high != ""){
            financingCondition.setAmount_high(Double.parseDouble(amount_high));
            financingCondition.setAmount_high(financingCondition.getAmount_high() * 10000);
        }
        if (create_time != null && create_time != "")
            financingCondition.setCreate_time(create_time);
        if (status != null && status != ""){
            if (status.equals("0"));
            if (status.equals("1"))
                financingCondition.setStatus("成功");
            if (status.equals("2"))
                financingCondition.setStatus("融资中");
            if (status.equals("3"))
                financingCondition.setStatus("失败");

        }
//        System.out.println("servlet层内"+no + "：" + instituty_id + "：" + amount_low + "：" + amount_high + "：" + create_time + "：" + status);
        PageHelper pageHelper = new PageHelper();
        if (whichPage != null)
            pageHelper.setWhichPage(Integer.parseInt(whichPage));
        pageHelper.setAllNum(financingService.selectFinancingCount(financingCondition));
        ArrayList<FinancingAndInstituty> financingAndInstituties = financingService.selectFinancingList(financingCondition, pageHelper);
        pageHelper.setList(financingAndInstituties);
        Gson gson = new Gson();
        try {
            response.getWriter().println(gson.toJson(pageHelper));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void queryAllInstituty(HttpServletRequest request, HttpServletResponse response){
        ArrayList<Instituty> instituties = institutyService.selectAllInstituty();
        Gson gson = new Gson();
        try {
            response.getWriter().println(gson.toJson(instituties));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void queryByVid(HttpServletRequest request, HttpServletResponse response){
        int id = Integer.parseInt(request.getParameter("id"));
        VoucherAndTwoEnterpriseAndInstituty voucherAndTwoEnterpriseAndInstituty = voucherService.selectVoucherDetail(id);
        Gson gson = new Gson();
        try {
            response.getWriter().println(gson.toJson(voucherAndTwoEnterpriseAndInstituty));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void queryById(HttpServletRequest request, HttpServletResponse response){
        int id = Integer.parseInt(request.getParameter("id"));
        FinancingAndInstituty financingAndInstituty = financingService.selectFinancingDetail(id);
        Gson gson = new Gson();
        try {
            response.getWriter().println(gson.toJson(financingAndInstituty));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void queryByVoucherCondition(HttpServletRequest request, HttpServletResponse response){
        String no = request.getParameter("no");
        String enterprise_id =request.getParameter("enterprise_id");
        String open_enterprise_id = request.getParameter("open_enterprise_id");
        String open_time =request.getParameter("open_time");
        String amount_low = request.getParameter("amount_low");
        String amount_high = request.getParameter("amount_high");
        String whichPage = request.getParameter("whichPage");

        VoucherCondition voucherCondition=new VoucherCondition();
        if(no != null && no!="")
            voucherCondition.setNo(no);
        if(enterprise_id != null && enterprise_id!="")
            voucherCondition.setEnterprise_id(Integer.parseInt(enterprise_id));
        if(open_enterprise_id != null && open_enterprise_id!="")
            voucherCondition.setOpen_enterprise_id(Integer.parseInt(open_enterprise_id));
        if(open_time != null && open_time!="")
            voucherCondition.setOpen_time(open_time);
        if(amount_low != null && amount_low!="") {
            voucherCondition.setAmount_low(Double.parseDouble(amount_low));
            voucherCondition.setAmount_low(voucherCondition.getAmount_low()*10000);
        }
        if(amount_high != null && amount_high!="") {
            voucherCondition.setAmount_high(Double.parseDouble(amount_high));
            voucherCondition.setAmount_high(voucherCondition.getAmount_high()*10000);
        }

        PageHelper pageHelper = new PageHelper();
        if (whichPage != null)
            pageHelper.setWhichPage(Integer.parseInt(whichPage));
        pageHelper.setAllNum(voucherService.selectVoucherCount(voucherCondition));
        ArrayList<VoucherAndTwoEnterpriseAndInstituty> voucherAndTwoEnterpriseAndInstituties=voucherService.selectVoucherList(voucherCondition, pageHelper);
        pageHelper.setList(voucherAndTwoEnterpriseAndInstituties);
        Gson gson=new Gson();
        try {
            response.getWriter().println(gson.toJson(pageHelper));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void queryEnterprise(HttpServletRequest request, HttpServletResponse response){

        ArrayList<Enterprise> enterprises = enterpriseService.selectAllEnterprise();
        Gson gson=new Gson();
        try {
            response.getWriter().println(gson.toJson(enterprises));
        } catch (IOException e) {

            e.printStackTrace();
        }

    }
    public void queryByNo(HttpServletRequest request, HttpServletResponse response){
        int id = Integer.parseInt(request.getParameter("id"));
        VoucherAndTwoEnterpriseAndInstituty voucherAndTwoEnterpriseAndInstituty = voucherService.selectVoucherDetail(id);
        Gson gson = new Gson();
        try {
            response.getWriter().println(gson.toJson(voucherAndTwoEnterpriseAndInstituty));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void updateVoucher(HttpServletRequest request, HttpServletResponse response){
        int vid = Integer.parseInt(request.getParameter("Vid"));
        int iid = Integer.parseInt(request.getParameter("Iid"));
        Voucher voucher = new Voucher();
        voucher.setId(vid);
        voucher.setInstituty_id(iid);
        boolean b = voucherService.updateVoucher(voucher);
        try {
            if (b == true)
                response.getWriter().println("修改成功！");
            else
                response.getWriter().println("修改失败！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void insertFinancing(HttpServletRequest request, HttpServletResponse response){
        Integer enterprise_id = Integer.parseInt(request.getParameter("id"));//融资企业id
        Double amount = Double.parseDouble(request.getParameter("amount"));//融资金额
        Double voucher_amount = Double.parseDouble(request.getParameter("voucher_amount"));//凭证金额
        Double cost = Double.parseDouble(request.getParameter("cost"));//融资成本
        Double receipt_amount = Double.parseDouble(request.getParameter("receipt_amount"));//预计到账金额
        Integer instituty_id = Integer.parseInt(request.getParameter("instituty_id"));//金融机构id
        Integer receipt_day = Integer.parseInt(request.getParameter("receipt_day"));//预计放款日期天数（int）
        String uplink_address = request.getParameter("uplink_address");//上链地址
        String payment_interest_type = request.getParameter("payment_interest_type");
        String remark = request.getParameter("remark");//备注
        boolean a = false, b = false;
        int id = financingService.selectFinancingCount(new FinancingCondition()) + 1;//获取最大id+1作为新id
        String no = (UUID.randomUUID().toString().substring(10, 20));
        Financing financing = new Financing();
        financing.setId(id);
        financing.setNo(no);
        financing.setEnterprise_id(enterprise_id);
        financing.setInstituty_id(instituty_id);
        financing.setCreate_time(countDate(0));
        financing.setReceipt_time(countDate(receipt_day));
        financing.setUplink_address(uplink_address);
        financing.setStatus("融资中");
        financing.setProgress_status("未放款");
        financing.setPayment_interest_type(payment_interest_type);
        financing.setRemark(remark);
        if (amount == voucher_amount){
            financing.setAmount(amount);
            financing.setCost(cost);
            financing.setReceipt_amount(receipt_amount);
        }else {
            financing.setAmount(amount);
            financing.setCost(cost * (amount / voucher_amount));
            financing.setReceipt_amount(receipt_amount * (amount / voucher_amount));
            Integer open_enterprise_id = Integer.parseInt(request.getParameter("open_enterprise_id"));
            String expiry_time = request.getParameter("expiry_time");
            String source = request.getParameter("source");
            id = voucherService.selectVoucherCount(new VoucherCondition()) + 1;//获取最大id+1作为新id
            Voucher voucher = new Voucher();
            voucher.setId(id);
            no = (UUID.randomUUID().toString().substring(10, 20));
            voucher.setNo(no);
            voucher.setAmount(voucher_amount - amount);
            voucher.setEnterprise_id(enterprise_id);
            voucher.setOpen_enterprise_id(open_enterprise_id);
            voucher.setInstituty_id(instituty_id);
            voucher.setOpen_time(countDate(0));
            voucher.setExpiry_time(expiry_time);
            voucher.setUplink_address(uplink_address);
            voucher.setSource(source);
            voucher.setStatus("已融资");
            if (source.equals("融资留存"))
                voucher.setSource_id(enterprise_id);
            voucher.setPayment_interest_type(payment_interest_type);
            a = voucherService.insertVoucher(voucher);
        }
        b = financingService.insertFinancing(financing);
        if (a == true)
            System.out.println("新建凭证成功");
        if (b == true)
            System.out.println("新建融资成功");
    }

    public String countDate(int days){
        SimpleDateFormat sdFormat = new SimpleDateFormat("yyyy-MM-dd");// 设置日期格式化
        Date currentDate = new Date(); // 获取当前日期

        Calendar calendar = Calendar.getInstance(); // 获取日历实例
        calendar.setTime(currentDate); // 设置日历的当前日期
        calendar.add(Calendar.DAY_OF_MONTH, days); // 将日历日期增加指定的天数

        Date newDate = calendar.getTime(); // 获取增加天数后的日期
        String formattedDate = sdFormat.format(newDate); // 格式化日期为字符串
        return formattedDate;
    }
}

